/**
 * 用户登录
 */
function login() {
    var user = $("#username").val();
    var password = $("#password").val();
    if (checkParams(user, password)) {
        loading(false);
        $.ajax({
            type: "POST",
            url: "/user",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(jsonParams("signIn",user,password)),
            dataType: "json",
            success: function (data) {
                loading(true);
                if (data.code == 0) {
                    sessionStorage.setItem("login",data.data);/*保存数据*/
                    window.location = "homepage.html";
                } else {
                    $("#tip-error").text(data.message).css("display", "block");
                }
            },
            error: function (message) {
                loading(true);
                $("#tip-error").text(message).css("display", "block");
            }
        });
    }
}

/**
 * 管理员登录
 */
function adminLogin() {
    var user = $("#username").val();
    var password = $("#password").val();
    if (checkParams(user, password)) {
        loading(false);
        $.ajax({
            type: "POST",
            url: "/user",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(jsonParams("admin",user,password)),
            dataType: "json",
            success: function (data) {
                loading(true);
                if (data.code == 0) {
                    sessionStorage.setItem("login",data.data);/*保存数据*/
                    window.location = "userManager.html";
                } else {
                    $("#tip-error").text(data.message).css("display", "block");
                }
            },
            error: function (message) {
                loading(true);
                $("#tip-error").text(message).css("display", "block");
            }
        });
    }
}


/**
 * 检查参数
 */
function checkParams(user, password) {
    var inspect = true;
    if (user.length == 0) {
        inspect = false;
        $("#tip-user").css("display", "block");
    } else {
        $("#tip-user").css("display", "none");
    }
    if (password.length == 0) {
        inspect = false;
        $("#tip-pwd").css("display", "block");
    } else {
        $("#tip-pwd").css("display", "none");
    }
    return inspect;
}

/**
 * 组装参数
 */
function jsonParams(param,username,password) {
    var json = {
        "param":param,
        "username":username,
        "password":password
    };
    return json;
}

/**
 * 隐藏显示加载框
 */
function loading(hide) {
    if (hide) {
        $("#loading").css("display", "none");
    } else {
        $("#loading").css("display", "block");
    }
}
$("#tip-error").css("display","none");
